package org.snail.attendence.job;

import org.apache.log4j.Logger;
import org.snail.attendence.bean.AliWorkDTO;
import org.snail.other.bean.ExtWorkSheet;
import org.snail.constant.WorkSheetConstant;
import org.snail.common.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by WJ on 2017/11/13.
 */
@Component
public class AttendanceJob {

    private static final Logger LOGGER =  Logger.getLogger(AttendanceJob.class);

    /**
     * 计算非工作日加班
     * @param aliWorkDTOList
     * @return
     */
    public List<ExtWorkSheet> computeExtWork(List<AliWorkDTO> aliWorkDTOList) throws Exception{
        LOGGER.debug("beging computeExtWork ....");
        List<ExtWorkSheet> extWorkSheetList = new ArrayList<ExtWorkSheet>();
        if(null!= aliWorkDTOList && !aliWorkDTOList.isEmpty()) {
            for (AliWorkDTO aliWorkDTO : aliWorkDTOList) {
                if(null!= aliWorkDTO) {
                    ExtWorkSheet extWorkSheet = computeExtWork(aliWorkDTO);
                    if(null!=extWorkSheet) {
                        extWorkSheetList.add(extWorkSheet);
                    }
                }
            }
        }
        LOGGER.debug("end computeExtWork ....");
        return extWorkSheetList;
    }

    /**
     * 计算非工作日加班
     * @param aliWorkDTO
     * @return
     */
    private ExtWorkSheet computeExtWork(AliWorkDTO aliWorkDTO) throws Exception{
        ExtWorkSheet extWorkSheet = null;
        //1.把阿里工时获取非工作日加班
        if(null!= aliWorkDTO && WorkSheetConstant.ORDER_FREE_TYPE.equals(aliWorkDTO.getOrder())){

            String approval = aliWorkDTO.getApproval();
            String dateStr = aliWorkDTO.getDateStr();
            String punchTime1 = aliWorkDTO.getPunchTime1();
            String punchTime2 = aliWorkDTO.getPunchTime2();
            String punchTime3 = aliWorkDTO.getPunchTime3();
            String punchTime4 = aliWorkDTO.getPunchTime4();

            String startTimeStr = "";
            String endTimeStr = "";
            if(!StringUtils.isEmpty(approval) || !StringUtils.isEmpty(punchTime1)){
                extWorkSheet = new ExtWorkSheet();
                extWorkSheet.setAliNumber(aliWorkDTO.getAliNumber());
                extWorkSheet.setEmployeeName(aliWorkDTO.getEmployeeName());
                //当关联的审批单不为空时，并且有上下班记录
                if(!StringUtils.isEmpty(approval)  &&  !StringUtils.isEmpty(punchTime1) && !StringUtils.isEmpty(punchTime2)){
                    Date startTime = getDate(dateStr, punchTime1);
                    Date endTime = null;
                    if(!StringUtils.isEmpty(punchTime4)) {
                        endTime = getDate(dateStr, punchTime4);
                    } else if(!StringUtils.isEmpty(punchTime3)) {
                        endTime = getDate(dateStr, punchTime3);
                    } else {
                        endTime = getDate(dateStr, punchTime2);
                    }
                    approval = getApprovalTimeStr(approval, WorkSheetConstant.APPROVAL_OVERTIME_TYPE);
                    if(!StringUtils.isEmpty(approval)) {
                        String[] approvalTimes = approval.split(WorkSheetConstant.SPLIT);
                        Date approvalStartTime =  DateUtils.parseDate(approvalTimes[0], DateUtils.DATE_FORMAT);
                        Date approvalEndTime = DateUtils.parseDate(approvalTimes[1], DateUtils.DATE_FORMAT);
                        approvalStartTime.setYear(startTime.getYear());
                        approvalEndTime.setYear(startTime.getYear());
                        if(DateUtils.dateCompare(approvalStartTime, startTime)) {
                            startTime = approvalStartTime;
                        }
                        if(!DateUtils.dateCompare(approvalEndTime, endTime)) {
                            endTime = approvalEndTime;
                        }
                        double hours = (endTime.getTime()-startTime.getTime())/(1000 * 60)/30/2.0;
                        startTimeStr = DateUtils.getReqDateStr(startTime);
                        endTimeStr = DateUtils.getReqDateStr(endTime);
                        extWorkSheet.setHours(Double.toString(hours));
                    }
                    extWorkSheet.setStartTime(startTimeStr);
                    extWorkSheet.setEndTime(endTimeStr);
                    extWorkSheet.setWorkType(WorkSheetConstant.EXT_WEEKEND_OVERTIME_TYPE);
                } else {
                    //有打卡时间转换打卡时间
                    if(!StringUtils.isEmpty(punchTime1)) {
                        startTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime1));
                    }

                    //有下班打卡时间转换打卡时间
                    if(!StringUtils.isEmpty(punchTime2)) {
                        if(!StringUtils.isEmpty(punchTime4)) {
                            endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime4));
                        } else if(!StringUtils.isEmpty(punchTime3)) {
                            endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime3));
                        } else {
                            endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime2));
                        }
                    }

                    extWorkSheet.setComments(approval);
                    extWorkSheet.setStartTime(startTimeStr);
                    extWorkSheet.setEndTime(endTimeStr);
                    extWorkSheet.setWorkType(WorkSheetConstant.EXT_EXCEPTION_TYPE);
                }
            }
        }
        return extWorkSheet;
    }



    /**
     * 替换审批内容
     * @param approvalStr
     * @return
     */
    private static  String getApprovalTimeStr(String approvalStr, String replace){
        if(null!=approvalStr) {
            approvalStr =  approvalStr.replaceAll(replace,"").replaceAll("到",WorkSheetConstant.SPLIT);
            approvalStr = approvalStr.substring(0, approvalStr.lastIndexOf(" "));
        }
        return approvalStr;
    }

    /**
     *  传入日期和时间，得到Date
     * @param dateStr 17-10-03 星期二
     * @param timeStr  HH:mm
     * @return
     */
    private Date processDate(String dateStr, String timeStr) {
        Date date = null;
        try {
            if(dateStr.contains(" ")) {
                dateStr =  dateStr.substring(0, dateStr.indexOf(" "));
                LOGGER.info("getDate is : " + dateStr);
                date = DateUtils.parseDate(dateStr, DateUtils.sdfDateOnly);
                Date hoursdate = DateUtils.parseDate(timeStr, DateUtils.HM_FORMAT);
                if(null!=date && null!=hoursdate) {
                    date.setHours(hoursdate.getHours());
                    date.setMinutes(hoursdate.getMinutes());
                }
            }
        } catch (ParseException e) {
            LOGGER.error(e.fillInStackTrace(), e);
        }
        return date;
    }

    /**
     * 计算工作日考勤
     * 1、工作日加班
     * 2、工作日异常考勤
     * @param aliWorkDTOList
     * @return
     */
    public List<ExtWorkSheet> computeOtherWork(List<AliWorkDTO> aliWorkDTOList) throws Exception{
        LOGGER.debug("beging computeExtWork ....");
        List<ExtWorkSheet> extWorkSheetList = new ArrayList<ExtWorkSheet>();
        if(null!= aliWorkDTOList && !aliWorkDTOList.isEmpty()) {
            for (AliWorkDTO aliWorkDTO : aliWorkDTOList) {
                if(null!= aliWorkDTO) {
                    ExtWorkSheet extWorkSheet = computeOtherWork(aliWorkDTO);
                    if(null!=extWorkSheet) {
                        extWorkSheetList.add(extWorkSheet);
                    }
                }
            }
        }
        LOGGER.debug("end computeExtWork ....");
        return extWorkSheetList;
    }

    /**
     * 计算非工作日加班
     * @param aliWorkDTO
     * @return
     */
    private ExtWorkSheet computeOtherWork(AliWorkDTO aliWorkDTO) throws Exception{
        ExtWorkSheet extWorkSheet = null;
        //把阿里工时获取非工作日加班
        if(null!= aliWorkDTO && !WorkSheetConstant.ORDER_FREE_TYPE.equals(aliWorkDTO.getOrder()) && !WorkSheetConstant.ORDER_OTHER_TYPE.equals(aliWorkDTO.getOrder())){
            boolean isNeedReturn = false;
            String approval = aliWorkDTO.getApproval();
            String dateStr = aliWorkDTO.getDateStr();
            String punchTime1 = aliWorkDTO.getPunchTime1();
            String punchTime2 = aliWorkDTO.getPunchTime2();
            String punchTime3 = aliWorkDTO.getPunchTime3();
            String punchTime4 = aliWorkDTO.getPunchTime4();

            String startTimeStr = "";
            String endTimeStr = "";

            if(!StringUtils.isEmpty(punchTime1) || !StringUtils.isEmpty(punchTime2)){
                extWorkSheet = new ExtWorkSheet();
                extWorkSheet.setAliNumber(aliWorkDTO.getAliNumber());
                extWorkSheet.setEmployeeName(aliWorkDTO.getEmployeeName());
                //当有上下班记录
                if(!StringUtils.isEmpty(punchTime1) && !StringUtils.isEmpty(punchTime2)){
                    Date startTime = getDate(dateStr, punchTime1);
                    Date endTime = null;
                    if(!StringUtils.isEmpty(punchTime4)) {
                        endTime = getDate(dateStr, punchTime4);
                    } else if(!StringUtils.isEmpty(punchTime3)) {
                        endTime = getDate(dateStr, punchTime3);
                    } else {
                        if(!StringUtils.isEmpty(punchTime2) && punchTime2.startsWith(WorkSheetConstant.NEXT_DAY)) {
                            punchTime2 = punchTime2.replace(WorkSheetConstant.NEXT_DAY, "");
                            endTime = getDate(dateStr, punchTime2);
                            endTime.setDate(endTime.getDate() + 1 );
                        } else {
                            endTime = getDate(dateStr, punchTime2);
                        }
                    }

                    //判断是否大于9小时
                    double hours = (endTime.getTime()-startTime.getTime())/(1000 * 60)/30/2.0;
                    if(hours<9.0) {
                        isNeedReturn = true;
                        extWorkSheet = setExtWorkSheet(extWorkSheet, dateStr, punchTime1, punchTime2, punchTime3, punchTime4);
                        extWorkSheet.setComments("考勤少于9小时");
                        extWorkSheet.setWorkType(WorkSheetConstant.EXT_EXCEPTION_TYPE);
                    } else {
                        //如果有审批
                        if(!StringUtils.isEmpty(approval)&& approval.startsWith(WorkSheetConstant.APPROVAL_OVERTIME_TYPE)){
                            isNeedReturn = true;
                            approval = getApprovalTimeStr(approval, WorkSheetConstant.APPROVAL_OVERTIME_TYPE);
                            String[] approvalTimes = approval.split(WorkSheetConstant.SPLIT);
                            Date approvalStartTime =  DateUtils.parseDate(approvalTimes[0], DateUtils.DATE_FORMAT);
                            Date approvalEndTime = DateUtils.parseDate(approvalTimes[1], DateUtils.DATE_FORMAT);
                            approvalStartTime.setYear(startTime.getYear());
                            approvalEndTime.setYear(startTime.getYear());
                            startTime = getDate(dateStr, WorkSheetConstant.OVERTIME_START);
                            if(DateUtils.dateCompare(approvalStartTime, startTime)) {
                                startTime = approvalStartTime;
                            }
                            if(!DateUtils.dateCompare(approvalEndTime, endTime)) {
                                endTime = approvalEndTime;
                            }
                            double overtimeHours = (endTime.getTime()-startTime.getTime())/(1000 * 60)/30/2.0;
                            startTimeStr = DateUtils.getReqDateStr(startTime);
                            endTimeStr = DateUtils.getReqDateStr(endTime);
                            extWorkSheet.setHours(Double.toString(hours));

                            extWorkSheet.setStartTime(startTimeStr);
                            extWorkSheet.setEndTime(endTimeStr);
                            extWorkSheet.setWorkType(WorkSheetConstant.EXT_WEEKDAY_OVERTIME_TYPE);
                        }
                    }
                } else {
                    //有缺卡时间记录
                    isNeedReturn = true;
                    extWorkSheet = setExtWorkSheet(extWorkSheet, dateStr, punchTime1, punchTime2, punchTime3, punchTime4);
                    extWorkSheet.setWorkType(WorkSheetConstant.EXT_EXCEPTION_TYPE);
                    extWorkSheet.setComments(approval);
                }
            }  else if(StringUtils.isEmpty(approval)  &&  StringUtils.isEmpty(punchTime1) && StringUtils.isEmpty(punchTime2)){

                extWorkSheet = new ExtWorkSheet();
                extWorkSheet.setAliNumber(aliWorkDTO.getAliNumber());
                extWorkSheet.setEmployeeName(aliWorkDTO.getEmployeeName());
                extWorkSheet.setComments(dateStr);
                extWorkSheet.setStartTime(startTimeStr);
                extWorkSheet.setEndTime(endTimeStr);
                extWorkSheet.setWorkType(WorkSheetConstant.EXT_EXCEPTION_TYPE);
                isNeedReturn = true;
            }  else if(!StringUtils.isEmpty(approval)){

                extWorkSheet = new ExtWorkSheet();
                extWorkSheet.setAliNumber(aliWorkDTO.getAliNumber());
                extWorkSheet.setEmployeeName(aliWorkDTO.getEmployeeName());
                extWorkSheet.setComments(dateStr + approval);
                extWorkSheet.setStartTime(startTimeStr);
                extWorkSheet.setEndTime(endTimeStr);
                extWorkSheet.setWorkType(WorkSheetConstant.EXT_OVERTIME_TYPE);
                isNeedReturn = true;
            }

            //不需要返回是，设置为null
            if(!isNeedReturn) {
                extWorkSheet = null;
            }
        }
        return extWorkSheet;
    }

    private  Date getDate(String dateStr ,String punchTime) throws Exception{
        Date time = null;
        if(!StringUtils.isEmpty(punchTime) && punchTime.startsWith(WorkSheetConstant.NEXT_DAY)) {
            punchTime = punchTime.replace(WorkSheetConstant.NEXT_DAY, "");
            time = processDate(dateStr, punchTime);
            time.setDate(time.getDate() + 1 );
        } else {
            time = processDate(dateStr, punchTime);
        }
        return  time;
    }

    private ExtWorkSheet setExtWorkSheet(ExtWorkSheet extWorkSheet,String dateStr, String punchTime1, String punchTime2, String punchTime3, String punchTime4) throws Exception{
        String startTimeStr = "";
        String endTimeStr = "";
        //有打卡时间转换打卡时间
        if(!StringUtils.isEmpty(punchTime1)) {
            startTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime1));
        }

        //有下班打卡时间转换打卡时间
        if(!StringUtils.isEmpty(punchTime2)) {
            if(!StringUtils.isEmpty(punchTime4)) {
                endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime4));
            } else if(!StringUtils.isEmpty(punchTime3)) {
                endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime3));
            } else {
                endTimeStr = DateUtils.getReqDateStr(getDate(dateStr, punchTime2));
            }
        }
        extWorkSheet.setStartTime(startTimeStr);
        extWorkSheet.setEndTime(endTimeStr);

        return extWorkSheet;
    }
}
